<template>
  <form class="w-50 m-auto mt-5">
    <div class="mb-3">
      <label for="field1" class="form-label">Имя пользователя или email</label>
      <input type="text" :class="'form-control ' + get_msg_class('login')" id="field1" aria-describedby="emailHelp"
        v-model="login" />
      <div class="invalid-feedback">
        {{ get_msg("login") }}
      </div>
    </div>
    <div class="mb-3">
      <label for="field2" class="form-label">Пароль</label>
      <input type="password" :class="'form-control ' + get_msg_class('password')" v-model="password" id="field2" />
      <div class="invalid-feedback">
        {{ get_msg("password") }}
      </div>
    </div>
    <!-- <div class="mb-3 form-check">
      <input type="checkbox" class="form-check-input" id="exampleCheck1" />
      <label class="form-check-label" for="exampleCheck1">Check me out</label>
    </div> -->
    <button type="button" class="btn btn-primary" @click="sendForm()">
      Отправить
    </button>
    <div class="col mt-3">
      <router-link to="/recover">Забыли пароль?</router-link>
    </div>

    <vue-basic-alert :duration="500" :closeIn="5000" ref="alert" />
  </form>
</template>

<script>
import VueBasicAlert from "vue-basic-alert";

export default {
  props: {
    tokens: Object,
    user: Object,
  },
  components: {
    VueBasicAlert
  },
  data() {
    return {
      login: "",
      password: "",
      detail: [],
    };
  },
  methods: {
    get_msg_class(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = "is-invalid";
        }
      });
      return ans;
    },
    get_msg(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = el.msg;
        }
      });
      return ans;
    },
    sendForm() {
      this.detail = [];
      fetch(`${process.env.VUE_APP_BASE_URI}/login/`, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          login: this.login,
          password: this.password,
        }),
      }).then(
        (resp) => {
          if (resp.status != 500) {
            resp.json().then(
              (body) => {
                if (resp.ok) {
                  let d = body;
                  // Складываем данные в local Storage
                  localStorage.setItem("tokens", JSON.stringify(d.tokens));
                  localStorage.setItem("user", JSON.stringify(d.user));
                  // Обновляем глобальное состояние данных
                  this.$emit("dataUpdate", d);
                  // Редирект на главную
                  this.$router.push("/");
                } else if (resp.status == 422) {
                  this.detail = body.detail;
                } else {
                  this.$refs.alert.showAlert(
                    "error",
                    `${body.detail}`,
                    "Ошибка"
                  );
                }
              },
              () => {
                this.$refs.alert.showAlert(
                  "error",
                  "Ошибка сервера",
                  "Ошибка обработки json"
                );
              }
            );
          } else {
            this.$refs.alert.showAlert("error", "Ошибка сервера", "500 error");
          }
        },
        (err) => {
          this.$refs.alert.showAlert(
            "error",
            "Ошибка сервера",
            err.message
          );
        }
      );
    },
  },
};
</script>

<style></style>